package com.cloxtec.scada.utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class LogHelper {

    @Resource
    private MongoHelper mongoHelper;

    private static long last_ts;
    private static int ndx;

    public LogHelper() {
        last_ts = 0;
        ndx = 0;
    }

    public void saveLog(String strMsg){
        JSONObject jsonLog = new JSONObject();
        jsonLog.put("msg", strMsg);
        saveLog(jsonLog);
    }

    public void saveLog(JSONObject jsonLog) {
        Date date = new Date();
        long ts = date.getTime();
        // 格式化日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String strDatetime = sdf.format(date);

        jsonLog.put("timestamp", ts);
        jsonLog.put("datetime", strDatetime);

        if (ts != last_ts) {
            ndx = 0;
        }
        String _id = strDatetime + "_" + ndx;
        ndx++;
        last_ts = ts;

        jsonLog.put("_id", _id);

        mongoHelper.save("log", jsonLog);
    }

}
